package com.eqs.enterprisequestionnaire.controller;

import com.eqs.enterprisequestionnaire.result.R;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    //配置文件上传路径
    public static final String basePath = "D/123456/images";


    /*
    * 上传文件
    * */
    @PostMapping("upload")
    public R<String> upload(MultipartFile file){

        //原始文件名
        String fileName =file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        //使用UUID重命名文件名称(方式文件重名或覆盖)
        String newFileName = UUID.randomUUID().toString()+suffix;

        // 使用日期解决同一文件夹中文件过多问题(以当前日期命名文件夹)
        String datePath =new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        //组装最终文件名
        String finalName = datePath+" "+newFileName;

        //创建目录
        File dir =new File(basePath);

        if (!dir.exists()){
            dir.mkdir();
        }
        try {
            file.transferTo(new File(basePath+finalName));
        } catch (IOException e){
            e.printStackTrace();
        }

        return R.success(finalName);
    }

    /*
    * 下载文件
    * */
    @GetMapping("download/{name}")
    public R<String> download(@PathVariable String name, HttpServletResponse response) {

        try {
            FileInputStream fileInputStream = new  FileInputStream(new File(basePath+name));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.success("success");
    }
}
